package entity

import "errors"

// UpdateGoodsStockSub 减库存
func UpdateGoodsStockSub(goods *Goods, selectedPropertyMap map[string]string, count int) error {
	for _, propertyInDB := range goods.PropertyList {
		selectedOption := selectedPropertyMap[propertyInDB.Name]
		if propertyInDB.IsMain {
			for _, option := range propertyInDB.Options {
				if selectedOption == option.Name {
					if option.Count < count {
						return errors.New("库存不够")
					}
					option.Count -= count
					return nil
				}
			}
			return errors.New("减库存失败，未选择主属性: " + propertyInDB.Name)
		}
	}
	// 如果没有主属性则使用goods的count字段
	if goods.Count < count {
		return errors.New("库存不够")
	}
	goods.Count -= count
	return nil
}

func UpdateGoodsStockAdd(goods *Goods, selectedPropertyMap map[string]string, count int) error {
	for _, propertyInDB := range goods.PropertyList {
		selectedOption := selectedPropertyMap[propertyInDB.Name]
		if propertyInDB.IsMain {
			for _, option := range propertyInDB.Options {
				if selectedOption == option.Name {
					option.Count += count
				}
				return nil
			}
			return errors.New("加库存失败，未选择主属性: " + propertyInDB.Name)
		}
	}
	// 如果没有主属性则使用goods的count字段
	goods.Count += count
	return nil
}
